<!--suppress HtmlDeprecatedAttribute -->
<template>
  <div class="wrapper">
    <order-refund-dialog v-model="dialogVisible" :order-id="refundOrderId" @change="dialogChange"/>
    <delivery-dialog v-model="deliveryDialogVisible" :order-id="deliveryOrderId"
                     :type='deliveryDialogType' @change="handleSendGoodSuccess"/>
    <logistics-dialog v-model="logisticsDialogVisible" :order-id="logisticsOrderId"/>
    <div class="top">
      <div class="left">
        <span class="title">订单列表</span>
      </div>
      <div class="right">
        <el-button size="mini" :icon="buttonsFlag ? 'el-icon-arrow-right' : 'el-icon-arrow-left'"
                   @click="buttonBox"/>
        <el-button v-if="buttonsFlag" @click="handleClearSort" size="small"
                   :disabled="paginationDisabled">清除排序</el-button>
        <el-button v-if="buttonsFlag" @click="handleClearFilter" size="small"
                   :disabled="paginationDisabled">清除筛选</el-button>
        <el-button @click="freshTable" size="small" icon="el-icon-refresh"
                   :disabled="paginationDisabled" :loading="paginationDisabled">刷新</el-button>
        <el-button @click="handleRemoveMore" type="danger" size="small" icon="el-icon-delete-solid"
                   :disabled="paginationDisabled ? '' : null">删除选择</el-button>
      </div>
    </div>
    <div class="table">
      <el-table ref="table" :data="tableData" style="width: 100%" height="449" max-height="600"
                v-loading='paginationDisabled' @selection-change="handleSelectionChange"
                :default-sort="tableSort" @sort-change="handleSortChange" :border="true"
                @filter-change="handleFilterChange">
        <el-table-column type="selection" align="center" width="50" fixed="left"/>
        <el-table-column prop="id" align="center" label="编号" columnKey="id" width="120"/>
        <el-table-column prop="name" align="center" label="商品" columnKey="name" width="200"
                :show-overflow-tooltip="true"/>
        <el-table-column prop="count" align="center" label="数量" columnKey="count" width="80"/>
        <el-table-column prop="createTime" align="center" label="创建时间" columnKey="createTime"
                         resizable width="180" sortable="custom"/>
        <el-table-column prop="goodsPrice" align="center" label="商品金额" columnKey="goodsPrice"
                         resizable width="110" sortable="custom"/>
        <el-table-column prop="freight" align="center" label="运费" columnKey="freight"
                         resizable width="80" sortable="custom"/>
        <el-table-column prop="freightInsu" align="center" label="运费险" columnKey="freightInsu"
                         resizable width="90" sortable="custom"/>
        <el-table-column prop="totalIntegral" align="center" label="积分" columnKey="totalIntegral"
                         resizable width="80" sortable="custom"/>
        <el-table-column prop="price" align="center" label="总金额" columnKey="price"
                         resizable width="100" sortable="custom"/>
        <el-table-column prop="state" align="center" label="状态" columnKey="state"
                         resizable width="100" sortable="custom" :filters="stateFilter"/>
        <el-table-column prop="payType" align="center" label="支付方式" columnKey="payType"
                         resizable width="110" :formatter="nullFormatter" sortable="custom"/>
        <el-table-column prop="payId" align="center" label="支付单号" columnKey="payId" sortable="custom"
                         resizable width="220" :show-overflow-tooltip="true" :formatter="nullFormatter"/>
        <el-table-column prop="priceTime" align="center" label="支付时间" columnKey="priceTime"
                         resizable width="180" :formatter="nullFormatter" sortable="custom"/>
        <el-table-column prop="endAddressDesc" align="center" label="收货地址" columnKey="endAddressDesc"
                         resizable width="300" :show-overflow-tooltip="true"/>
        <el-table-column prop="message" align="center" label="留言" columnKey="message"
                         resizable width="80" :show-overflow-tooltip="true"/>
        <el-table-column prop="remark" align="center" label="备注" columnKey="remark"
                         resizable width="80" :show-overflow-tooltip="true"/>
        <el-table-column label="操作" align="center" fixed="right" resizable width="140">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="handleDialogDetail(scope.row)">详情</el-button>
            <el-button type="text" size="small" @click="handleSendGood(scope.row)"
                       v-if="scope.row.state === orderStateCode.STATE_TO_TRANS">发货</el-button>
            <el-button type="text" size="small" @click="handleShowLogistics(scope.row)"
                       v-if="scope.row.state === orderStateCode.STATE_TO_TRANSPORTING
                       || scope.row.state === orderStateCode.STATE_TO_RECEIVE">物流</el-button>
            <el-button type="text" size="small" @click="handleChangeSendGood(scope.row)"
                       v-if="scope.row.state === orderStateCode.STATE_TO_TRANSPORTING
                       || scope.row.state === orderStateCode.STATE_TO_RECEIVE">修改</el-button>
            <el-button type="text" size="small" @click="handleRefund(scope.row)"
                       v-if="scope.row.state === orderStateCode.STATE_TO_REFUND">退款</el-button>
            <el-button type="text" style="color: red" size="small" @click="handleRemove(scope.row)"
                       v-if="scope.row.state === orderStateCode.STATE_REFUNDED
                       || scope.row.state === orderStateCode.STATE_CANCEL
                       || scope.row.state === orderStateCode.STATE_RECEIVED
                       || scope.row.state === orderStateCode.STATE_END">
              移除订单
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change='handleCurrentChange'
                     :page-size.sync='size' :total.sync="total" :current-page.sync="page" background
                     :disabled="paginationDisabled"
                     layout="sizes, total, jumper, prev, pager, next"/>
    </div>
  </div>
</template>

<script>
// noinspection JSUnusedGlobalSymbols
import OrderStateCode, { OrderStateFilter } from '@/constants/OrderStateCode'
import { ResultCode } from '@/constants/constants'
import PageDTO from '@/api/entity/PageDTO'
import StoreOrderDetailQueryDTO from '@/api/entity/StoreOrderDetailQueryDTO'
import { queryOrderDetailPageWrapperStore, removeOrderStoreById } from '@/api/ApiOrderDetail'
import { formatTime } from '@/utils/ConvertData'
import OrderRefundDialog from '@pages/order/part/pageOrderList/OrderRefundDialog'
import DeliveryDialog from '@pages/order/part/pageOrderList/DeliveryDialog'
import LogisticsDialog from '@pages/order/part/pageOrderList/LogisticsDialog'

export default {
  name: 'PageOrderList',
  components: { LogisticsDialog, DeliveryDialog, OrderRefundDialog },
  data () {
    return {
      orderStateCode: OrderStateCode,
      buttonsFlag: true,
      tableSort: {},
      tableData: [],
      selection: [],
      sortData: this.tableSort,
      filterData: {},
      loading: false,
      total: 0,
      size: 10,
      page: 1,
      refundOrderId: 0,
      deliveryOrderId: 0,
      logisticsOrderId: 0,
      dialogVisible: false,
      deliveryDialogVisible: false,
      logisticsDialogVisible: false,
      deliveryDialogType: 'add',
      stateFilter: OrderStateFilter
    }
  },
  computed: {
    paginationDisabled () {
      return this.loading
    },
    selectIds () {
      const ids = []
      this.selection.forEach(item => {
        ids.push(item.id)
      })
      return ids
    }
  },
  methods: {
    /**
     * 查看订单详情
     */
    handleDialogDetail (val) {
      // todo 查看订单详情
    },
    /**
     * 发货
     */
    handleSendGood (val) {
      this.deliveryOrderId = val.id
      this.deliveryDialogType = 'add'
      this.deliveryDialogVisible = true
    },
    /**
     * 修改发货信息
     */
    handleChangeSendGood (val) {
      this.deliveryOrderId = val.id
      this.deliveryDialogType = 'change'
      this.deliveryDialogVisible = true
    },
    /**
     * 查看订单物流信息
     */
    handleShowLogistics (val) {
      this.logisticsOrderId = val.id
      this.logisticsDialogVisible = true
    },
    /**
     * 发货成功
     */
    handleSendGoodSuccess () {
      this.freshTable()
    },
    /**
     * 退款
     */
    handleRefund (val) {
      this.refundOrderId = val.id
      this.dialogVisible = true
    },
    nullFormatter (row, column, cellValue) {
      return cellValue && cellValue !== 'null' && cellValue !== 'undefined' ? cellValue : '无'
    },
    buttonBox () {
      this.buttonsFlag = !this.buttonsFlag
    },
    /**
     * 移除一个数据
     * @param val 数据
     */
    handleRemove (val) {
      this.$confirm('此操作将永久删除该订单信息, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const id = val.id
        if (id) {
          removeOrderStoreById(id, data => {
            if (data && data.code === ResultCode.OK) {
              this.$message.success('移除订单成功')
              this.freshTable()
            }
          }, () => {})
        } else {
          this.$message.error('错误的订单编号 ' + id)
        }
      }).catch(() => {
      })
    },
    /**
     * 清除排序
     */
    handleClearSort () {
      this.$refs['table'].clearSort()
      this.sortData = {}
      this.freshTable()
    },
    /**
     * 清除筛选
     */
    handleClearFilter () {
      this.$refs['table'].clearFilter()
      this.filterData = {}
      this.page = 1
      this.freshTable()
    },
    /**
     * 移除选择的多个数据
     */
    handleRemoveMore () {
      if (this.selectIds.length === 0) {
        this.$message.error('请先选择希望移除的商品')
        return
      }
      this.$confirm('此操作将永久删除这' + this.selectIds.length + '条商品信息，包括子商品信息及上传图片，是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // todo
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    /**
     * 选择发生改变回调，同步数据
     * @param val 选择的数据，数组
     */
    handleSelectionChange (val) {
      this.selection = val
    },
    /**
     * 数据转换
     */
    convertOrderDetail (item) {
      item.createTime = formatTime(item['createTime'])
      item.priceTime = formatTime(item['priceTime'])
      item.totalIntegral = item['integral']
      const list = item['list']
      if (list && typeof list === 'object') {
        item.name = list[0]['goodName'] + '|' + list[0]['subGoodName']
        item.count = 0
        list.forEach(sub => {
          item.count += sub.count
        })
      }
      return item
    },
    /**
     * 更新表格数据，size和page改变时都会调用
     */
    freshTable () {
      this.loading = true
      const pageDTO = PageDTO.instance()
      pageDTO.setSize(this.size)
      pageDTO.setCurrent(this.page)
      const condition = StoreOrderDetailQueryDTO.instance()
      // 排序
      if (this.sortData && this.sortData.prop && this.sortData.order) {
        if (this.sortData.order === 'descending') {
          condition.addOrderDesc(this.sortData.prop)
        } else if (this.sortData.order === 'ascending') {
          condition.addOrderAsc(this.sortData.prop)
        }
      }
      // 筛选
      Object.keys(this.filterData).forEach(key => {
        const value = this.filterData[key]
        if (value && value.length > 0) {
          if (key === 'state') {
            condition.setState(value)
          }
        }
      })
      pageDTO.setCondition(condition)
      queryOrderDetailPageWrapperStore(pageDTO, data => {
        if (data.code === ResultCode.OK) {
          const tableData = data.object['records']
          const list = []
          tableData.forEach(item => {
            list.push(this.convertOrderDetail(item))
          })
          this.tableData = list
          this.total = data.object['total']
        }
      }, () => {
        this.loading = false
      })
    },
    /**
     * size改变更新数据
     */
    handleSizeChange () {
      this.page = 1
      this.freshTable()
    },
    /**
     * 排序改变监听，刷新页面
     * { column, prop, order }
     */
    handleSortChange (val) {
      this.sortData = val
      this.freshTable()
    },
    /**
     * 筛选改变监听
     */
    handleFilterChange (val) {
      Object.assign(this.filterData, val)
      this.page = 1
      this.freshTable()
    },
    /**
     * page改变更新数据
     */
    handleCurrentChange () {
      this.freshTable()
    },
    /**
     * 退款成功后更新数据
     */
    dialogChange () {
      this.freshTable()
    }
  },
  /**
   * 初始化更新数据
   */
  mounted () {
    this.freshTable()
  }
}
</script>

<style lang="scss" scoped>

  .wrapper {

    .top {

      width: 100%;
      height: 50px;
      border-bottom: 1px solid #999999;
      margin-bottom: 8px;

      .left {
        display: inline-block;
        width: 20%;
        text-align: left;
      }

      .right {
        display: inline-block;
        width: 80%;
        text-align: right;
      }

    }

    .table {
      margin: 16px 0;
      text-align: center;

      .pagination {
        margin: 20px auto;
      }
    }

  }

</style>
